<template>
  <main>
    <van-form validate-first @submit="submitForm('codeForm')" class="codeForm">
      <van-field
        placeholder="请输入手机号"
        clearable
        type="number"
        maxlength="11"
        v-model="codeForm.phoneNum"
        :rules="phoneValidator"
      >
        <template #left-icon> <i class="el-icon-mobile"></i> </template
      ></van-field>
      <van-field
        left-icon="el-icon-message"
        placeholder="请输入验证码"
        type="number"
        :center="true"
        maxlength="6"
        label-class="m-r-5"
        class="msg-code"
        v-model="codeForm.msgCode"
        autocomplete="off"
      >
        <template #left-icon> <i class="el-icon-message"></i> </template>
        <template #button>
          <van-button
            @click="sendCode()"
            native-type="button"
            :disabled="!isSendCodeActive"
            :class="'send-code f14' + (isSendCodeActive ? ' is-active' : '')"
            type="default"
            >{{ sendMsg }}</van-button
          >
        </template></van-field
      >
      <div class="forget-fake-sigin-content">
        <span>未注册将自动创建智慧云账号</span>
      </div>
      <van-button
        block
        type="info"
        v-if="useLoadingButton"
        :disabled="isBadSubmit"
        :loading="loading"
        class="f16"
        native-type="submit"
        >{{ submitText }}</van-button
      >
      <van-button
        block
        type="info"
        v-else
        class="f16"
        :disabled="isBadSubmit"
        native-type="submit"
        >{{ submitText }}</van-button
      >
      <div class="operate-pass">
        <van-checkbox
          v-model="agreeDoc"
          class="f12"
          ref="docCheck"
          icon-size="12px"
          checked-color="#0080ff"
          >阅读并接受
          <a style="color: #0080ff" @click.prevent="openDoc"
            >《荣大科技用户协议》</a
          >
        </van-checkbox>
      </div>
    </van-form>
  </main>
</template>

<script>
import { getRSAKey, sendAuthCode } from 'api/modules/login.api';
import { loginByMobile } from 'api/modules/loginMobile.api';

// 验证码计时器倒计时时间
const COUNT_DOWN_NUMBER = 60;

export default {
  name: 'vertify-code',
  data() {
    const validatePhone = (value) => {
      this.badPhoneNum = true;
      if (this.phoneNumLegal(value)) {
        this.badPhoneNum = false;
        return true;
      }
      return false;
    };
    return {
      codeForm: {
        phoneNum: '',
        msgCode: '',
      },
      countDownNum: COUNT_DOWN_NUMBER,
      agreeDoc: false,
      phoneValidator: [
        {
          validator: validatePhone,
          message: '请输入有效的手机号码',
          trigger: 'onBlur',
        },
      ],
      // 存放计时器
      timeObj: {},
      loading: false,
      badPhoneNum: true,
      sendMsg: '发送验证码',
      sendCodeLoaing: false,
    };
  },
  props: {
    submitText: {
      type: String,
      default: '提交',
    },
    linkFlag: {
      type: Boolean,
      default: false,
    },
    notUseLoginPost: {
      type: Boolean,
      default: false,
    },
    useLoadingButton: {
      type: Boolean,
      default: true,
    },
  },
  watch: {
    'codeForm.phoneNum': {
      handler(newVal) {
        this.badPhoneNum = !this.phoneNumLegal(newVal);
      },
    },
  },
  computed: {
    // 判断发送验证码是否可点
    isSendCodeActive() {
      return (
        // 如果时间归零 或 未开始计时， 发送验证码按钮可点
        (this.countDownNum === 0 || this.countDownNum === COUNT_DOWN_NUMBER) &&
        !this.badPhoneNum &&
        !this.sendCodeLoaing
      );
    },
    // 判断是否登录可点击
    isBadSubmit() {
      return !this.codeForm.msgCode || this.badPhoneNum;
    },
  },
  beforeDestroy() {
    clearTimeout(this.timeObj.codeCount);
  },
  mounted() {},
  methods: {
    openDoc() {
      // 待优化，下面硬写点击打开协议不触发checkbox选中
      window.open(
        'http://ibsaas-crm.rongdasoft.com:19002/registAgreement',
        '__blank'
      );
      setTimeout(() => {
        this.$refs.docCheck.toggle();
      }, 10);
    },
    vaildPhone() {},
    submitForm() {
      if (!this.agreeDoc) {
        this.$toast('请先勾选并同意荣大科技用户协议');
        return;
      }
      this.handleLogin();
    },
    async handleLogin() {
      this.loading = true;
      const { phoneNum, msgCode } = this.codeForm;
      const params = {
        data: {
          mobile: phoneNum,
          authCode: msgCode,
          linkFlag: this.linkFlag,
        },
        loginType: 'web',
      };
      this.$set(params, 'mode', 'codeLogin');
      this.$emit('beforeLogin', params);
      if (this.notUseLoginPost) {
        return;
      }
      const response = await loginByMobile(params);
      const { msg, code } = response;
      if (code !== 0) {
        this.$toast(msg);
        this.loading = false;
      }
      this.$emit('submitForm', response);
    },
    // 没有publicKeyCode，重新获取
    async rsaFailure() {
      const { data } = await getRSAKey();
      if (!data) {
        this.$toast.fail('系统异常，请刷新重试');
        return;
      }
      this.sendCode(data);
    },
    // 发送验证码
    async sendCode(newKeyCode = undefined) {
      if (!this.isSendCodeActive) {
        return;
      }
      this.sendCodeLoaing = true;
      if (!this.globalProcessData.getPublicKey() && !newKeyCode) {
        // 没有publicKeyCode，重新获取
        this.rsaFailure();
        return;
      }

      const params = {
        data: {
          mobile: this.codeForm.phoneNum,
        },
      };
      // 将data数据加密并封装为request再请求接口
      const request = this.$loginUtils.handleEncryptionRequest(
        params,
        // 如果公钥不存在则使用刷新的公钥
        newKeyCode || this.globalProcessData.getPublicKey()
      );
      const response = await sendAuthCode(request).catch(() => {});
      if (response.code !== 0) {
        this.$toast({
          message: response.msg,
          type: 'fail',
        });
        this.sendCodeLoaing = false;
        return;
      }
      this.$toast({
        message: '发送短信成功',
        type: 'success',
      });
      if (this.timeObj.codeCount) {
        clearTimeout(this.timeObj.codeCount);
      }
      window.sessionStorage.setItem(
        'time_' + location.href,
        new Date().getTime()
      );
      this.countDownFn(this.countDownNum);
      // this.countDownNum--;
    },
    // 倒计时
    countDownFn(time) {
      this.countDownNum = time;
      if (time === 0) {
        this.sendMsg = '重新发送';
        this.countDownNum = COUNT_DOWN_NUMBER;
        this.sendCodeLoaing = false;
        return;
      }
      this.countDownNum--;
      // 当前时间
      const nowTime = new Date().getTime();
      // 上次缓存时间
      const lastTime = window.sessionStorage.getItem('time_' + location.href);
      // 两次时间差
      const diff = nowTime - lastTime / 1000;
      if (diff < 60) {
        this.countDownNum = 60 - diff;
      }
      this.sendMsg = `剩余${this.countDownNum}秒`;
      this.timeObj.codeCount = setTimeout(() => {
        this.countDownFn(this.countDownNum);
      }, 1000);
    },
    // 判断手机号是否合法
    phoneNumLegal(str) {
      const check = /^1[3456789]\d{9}$/;
      return check.test(str);
    },
  },
};
</script>

<style lang="less" scoped>
.is-active {
  color: #0062ff;
  cursor: pointer;
}
.codeForm {
  .operate-pass {
    margin-top: 12px;
    color: #606266;
    > a {
      cursor: pointer;
      font-size: 12px;
    }
    margin-bottom: 36px;
  }
}
.forget-fake-sigin-content {
  height: 16px;
  margin-bottom: 24px;
  text-align: center;
  font-weight: 400;
  font-size: 12px;
  color: #909399;
}
</style>

<style lang="less">
.codeForm {
  .msg-code {
    .van-button--default {
      border-width: 0;
    }
  }
}
</style>
